<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/departmenthead/DepartmentHeadAction.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class IndicatorValueUpdateAction extends DepartmentHeadAction {
	protected function execute(Response $response) {
		// Определение года, для которого выполняется сохранение целевых показателей
		if(isset($_SESSION['year']) && isset($_SESSION['user'])) {
			$year = unserialize($_SESSION['year']);
			// Получение данных для соответствующих подразделений и календарного года
			$serviceFactory = new ServiceFactory();
			$service = $serviceFactory->getService('DepartmentService');
			$departments = $service->findByHead(unserialize($_SESSION['user']));
			$service = $serviceFactory->getService('ResponsibilityService');
			$responsibilities = array();
			foreach($departments as $department) {
				$responsibility = $service->getByDepartmentAndYear($department->getIdentity(), $year);
				foreach($responsibility as $value){
					if(!$value->isMonitoring()) {
						$responsibilities[] = $value;
					}
				}
			}
			$indicatorValues = array();
			$service = $serviceFactory->getService('IndicatorValueService');
			foreach($responsibilities as $value){
				$indicatorValuesTemp = $service->getByResponsibility($value->getIdentity());
				foreach($indicatorValuesTemp as $indicatorValue) {
					$indicatorValues[] = $indicatorValue;
				}
			}
			foreach($indicatorValues as $indicatorValue) {
				if(isset($_POST['indicator-'.$indicatorValue->getIdentity()])) {
					$indicatorValue->setValue($_POST['indicator-'.$indicatorValue->getIdentity()]);
				}
				if(isset($_POST['indicatorPlan-'.$indicatorValue->getIdentity()])) {
					$indicatorValue->setPlanValue($_POST['indicatorPlan-'.$indicatorValue->getIdentity()]);
				}
				$service->save($indicatorValue);
			}
		}
		$response->setActionPath('/editing/division/index.html');
	}
}
?>